import { useEffect, useState } from 'react'
import { Outlet, useLocation, useNavigate } from 'react-router-dom'
import { checkRouterAuth } from './index'
import { isAuthToken } from '@utils'

const RouterBeforeEach = () => {
    const location = useLocation()
    const navigator = useNavigate()
    const [auth,setAuth] = useState(false)
    useEffect( () => {
        let obj = checkRouterAuth(location.pathname)
        const isLogin = Boolean(isAuthToken())
        if (obj && obj.auth && isLogin == false) {
            setAuth(false)
            navigator('/login', { replace: true})
        } else {
            setAuth(true)
        }
    } , [])
    return auth ? <Outlet/> : null
}

export default RouterBeforeEach